from django_redis import get_redis_connection
from rest_framework import serializers
from oauth.models import OAuthQQUser
from oauth.utils import check_access_token
from users.models import User


class OAuthQQUserSerializer(serializers.Serializer):

    mobile = serializers.RegexField(regex='1[3-9]\d{9}', label='手机号', required=True)
    password = serializers.CharField(label='密码', required=True)
    sms_code = serializers.CharField(max_length=6, min_length=6, required=True)
    access_token = serializers.CharField()

    def validate(self, attrs):

        access_token = attrs.get("access_token")
        openid = check_access_token(access_token)

        if openid is None:
            raise serializers.ValidationError('绑定时效过期')

        attrs["openid"] = openid

        sms_code = attrs.get("sms_code")
        mobile = attrs.get('mobile')
        redis_conn = get_redis_connection('code')
        redis_sms_code = redis_conn.get('sms_%s' % mobile)

        if redis_sms_code is None:
            raise serializers.ValidationError('短信验证码已过期')

        if redis_sms_code.decode() != sms_code:
            raise serializers.ValidationError('短信验证码错误')

        try:
            user = User.objects.get(mobile= mobile)
        except User.DoesNotExist:
            pass
        else:
            if not user.check_password(attrs.get('password')):
                raise serializers.ValidationError('密码不正确')

            attrs["user"] = user

        return attrs

    def create(self, validated_data):

        user = validated_data.get("user")
        openid = validated_data.get("openid")

        if user is None:
            user = User.objects.create(
                username = validated_data.get("mobile"),
                mobile =validated_data.get("mobile"),
                password = validated_data.get("password")
            )

            user.set_password  = (validated_data.get("password"))
            user.save()

        qquser = OAuthQQUser.objects.create(
            user=user,
            openid=openid
        )

        return qquser